class List{
    constructor(){
    this.getData();
    this.changeName();
    this.logout();
    this.current();
    this.paging();
    }

    paging(){
      let pageNum = window.location.search;
      let page = pageNum.split('?')[1];

    //   console.log(page);
      this.getData(page);
      let objs = this.$('.page_span1 a');
      objs.forEach(ele=>{
        if(ele.classList.contains('active')){
            ele.classList.remove('active')
        }
        if(ele.innerHTML==page) ele.classList.add('active');
      })
    }

    //获取商品信息
async getData(id = 1){
    let { status,data } = await axios.get('http://localhost:8888/goods/list?current='+id);
    // console.log(res);
    // console.log(data.yourParams.current);
    //判断服务器状态
    if(status!=200||data.code!=1) return;
    //遍历商品信息
    let html = '';
    data.list.forEach(ele => {
        // console.log(ele);
        html +=`<div class="mingxing">
        <div class="sub_mingxing" id="goods"><a href="./detail.html?${ ele.goods_id }"><img src="${ ele.img_big_logo
        }" alt=""></a></div>
        <div class="pinpai"><a href="#none">${ ele.title }</a></div>
        <div class="youhui">搭载澎湃S1 八核高性能处理器</div>
        <div class="jiage">${ ele.price }</div>
        <button href="#none" class="sk_goods_buy" onclick="List.nowBuy(${ele.goods_id})" style="margin-left:35%">立即抢购</button>
      </div>`
    });
    this.$('.main').innerHTML = html ;
    if(id==1){
        this.$('.nb-one').classList.add('active')
    }else{
        this.$('.nb-one').classList.remove('active')
    }
}
    

    //分页的实现
    current(){
      //给他们共同的父级添加点击事件,实现事件委托
      this.$('.page_wrap').addEventListener('click',this.toCurrent.bind(this));
     
    }


    //判断点击的是什么
    toCurrent(ele){
        let tar = ele.target;
        if (tar.classList.contains('num')) {
            this.checkPaging(tar);
        }
        //上下页
        if (tar.classList.contains('previous')) {
            this.previousPage(tar);
        }
        if (tar.classList.contains('next')) {
            this.nextPage(tar);
        }
    }

     //点击数字
    async checkPaging(tar){
        let objs = this.$('.page_span1 a');
        // console.log(objs);
        objs.forEach(ele=>{
            ele.classList.remove('active');
        })
          
        //    console.log(tar);
        tar.classList.add('active');
           let page = tar.innerHTML;
        //    console.log(page);
           let { data } = await axios.get('http://localhost:8888/goods/list',{
               params:{
                current:page
            }
           })
    
           let html = '';
           data.list.forEach(ele => {
            // console.log(ele);
            html +=`<div class="mingxing">
            <div class="sub_mingxing" id="goods"><a href="./detail.html?${ ele.goods_id }"><img src="${ ele.img_big_logo
            }" alt=""></a></div>
            <div class="pinpai"><a href="#none">${ ele.title }</a></div>
            <div class="youhui"></div>
            <div class="jiage">${ ele.price }</div>
            <button href="#none" class="sk_goods_buy" onclick="List.nowBuy(${ele.goods_id})" style="margin-left:35%">立即抢购</button>
          </div>`
        });
        this.$('.main').innerHTML = html ;
    
     }

    async previousPage(tar){
        // console.log(22222);
        // console.log(tar);
        // console.log(this.$('.active'));
       let res =  this.$('.active')[1];
    //    console.log(res);
          let  num = res.innerHTML;
           num--;
           if(num<1) return
           res.classList.remove('active');
           res.previousElementSibling.classList.add('active');
        //    console.log(res,num);
        let { data } = await axios.get('http://localhost:8888/goods/list',{
               params:{
                current:num
            }
           })
    
           let html = '';
           data.list.forEach(ele => {
            // console.log(ele);
            html +=`<div class="mingxing">
            <div class="sub_mingxing" id="goods"><a href="./detail.html?${ ele.goods_id }"><img src="${ ele.img_big_logo
            }" alt=""></a></div>
            <div class="pinpai"><a href="#none">${ ele.title }</a></div>
            <div class="youhui"></div>
            <div class="jiage">${ ele.price }</div>
            <button href="#none" class="sk_goods_buy" onclick="List.nowBuy(${ele.goods_id})" style="margin-left:35%">立即抢购</button>
          </div>`
        });
        this.$('.main').innerHTML = html ;
     }
     async nextPage(tar){
        // console.log(22222);
        // console.log(tar);
        // console.log(this.$('.active'));
       let res =  this.$('.active')[1];
    //    console.log(res);
          let  num = res.innerHTML;
           num++;
           if(num>9) return
        //    console.log(num);
           res.classList.remove('active');
           res.nextElementSibling.classList.add('active');
        //    console.log(res,num);
        let { data } = await axios.get('http://localhost:8888/goods/list',{
               params:{
                current:num
            }
           })
    
           let html = '';
           data.list.forEach(ele => {
            // console.log(ele);
            html +=`<div class="mingxing">
            <div class="sub_mingxing" id="goods"><a href="./detail.html?${ ele.goods_id }"><img src="${ ele.img_big_logo
            }" alt=""></a></div>
            <div class="pinpai"><a href="#none">${ ele.title }</a></div>
            <div class="youhui"></div>
            <div class="jiage">${ ele.price }</div>
            <button href="#none" class="sk_goods_buy" onclick="List.nowBuy(${ele.goods_id})" style="margin-left:35%">立即抢购</button>
          </div>`
        });
        this.$('.main').innerHTML = html ;
     }


static nowBuy(goodsId){
    // console.log(1111);
    //判断是否有token
     let token = localStorage.getItem('token')
     if(!token)location.assign='./login.html'
     
     //将商品加入购物车
     let userId = localStorage.getItem('user_id');
     let param = `id=${userId}&goodsId=${goodsId}`
    //  console.log(userId,goodsId);
     axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    axios.defaults.headers.common['Authorization'] = token;
    //发送ajax请求
    axios.post('http://localhost:8888/cart/add',param).then(res=>{
                //  console.log(res);
        let { status,data } = res;
        if(status!=200) return;
        if(data.code == 0) location.assign('./login.html');

        //提示下一步操作
        layer.confirm('是否去购物车结算', {
            btn: ['去','不去'], //按钮
            shade: false //不显示遮罩
        }, function(){
            location.assign('./cart.html')
        });
    })
}

//登陆后显示用户名
async changeName(){
    let userId = localStorage.getItem('user_id');
    // console.log(userId);
    axios.defaults.headers['authorization'] = 'application/x-www-form-urlencoded';
   let { status,data } = await axios.get('http://localhost:8888/users/info?id='+userId);
//    console.log(data.info.nickname);
     let username = data.info.nickname;
     if(status!=200) return
     let user = this.$('.username');
    //  console.log(user);
    let param = `${ username }<i class="iconfont icon-jiantou_xiangxia1"></i>`
     user.innerHTML = param;
     let token = localStorage.getItem('token');
     console.log(token);
     if(!token){
        user.innerHTML = '请登录';
        location.assign('./login.html?returnUrl=./search.html')
     }
}
     //退出登陆
     logout(){
        this.$('.goHome').addEventListener('click',this.userLogout);
        // let res = this.$('.gohome');
        // console.log(res);
     }
      userLogout=()=>{
        // console.log(11111);
        // 发送ajax请求
        let userId = localStorage.getItem('user_id');
        console.log(userId);
        let res = axios.get('http://localhost:8888/users/logout?id='+userId).then(()=>{
           location.assign('./search.html')
        });
        // console.log(res);
     }
//封装获取节点的方法
$(ele){
    let res = document.querySelectorAll(ele);
    return res.length==1 ? res[0] : res;
}
}

new List;